//CS 564:: PROJECT STAGE 5 - RDBS Catalog
//
// Caela Northey (caela) 905 653 2238
// Colin Laska   (laska) 906 150 7258

#include "catalog.h"
#include "query.h"

/*
 * Deletes records from a specified relation.
 *
 * Returns:
 * 	OK on success
 * 	an error code otherwise
 */

const Status QU_Delete(const string & relation, 
		       const string & attrName, 
		       const Operator op,
		       const Datatype type, 
		       const char *attrValue)
{

  if (relation.empty())
    return BADCATPARM;

  Status status;
  RID rid;
  HeapFileScan *hfs;
  AttrDesc attr_rec;

  // Used in the switch
  int tmp_int;
  int tmp_float;

  // Get information about the attrName
  status = attrCat->getInfo(relation, attrName, attr_rec);
  if (status != OK){
    return status;
  }

  // Create heap file scan on the relation
  hfs = new HeapFileScan(relation, status);
  if (status != OK){
    return status;
  }

  // Set up the startScan
  // NOTE: cannot initialize values in the switch without having
  // '{' and '}' surround the cases
  switch (type)
  {
    case INTEGER:
      tmp_int = atoi(attrValue);
      status = hfs->startScan(attr_rec.attrOffset, attr_rec.attrLen,
                              type, (char*)&tmp_int, op);
      if (status != OK){
        return status;
      }
      break;

    case FLOAT:
      tmp_float = atof(attrValue);
      status = hfs->startScan(attr_rec.attrOffset, attr_rec.attrLen,
                              type, (char*)&tmp_float, op);
      if (status != OK){
        return status;
      }
      break;

    case STRING:
      status = hfs->startScan(attr_rec.attrOffset, attr_rec.attrLen,
                              type, attrValue, op);
      if (status != OK){
        return status;
      }
      break;
  }

  // Scan through the heapfile looking for records to delete
  while (1){
    status = hfs->scanNext(rid);
    if(status == FILEEOF){
      break; // For now just break if we reach the end without finding anything
    }
    else if (status != OK){
      return status;
    }

    //Recall: const Status deleteRecord() deletes record in curRec
    //which was placed there by a preceding scanNext() call
    status = hfs->deleteRecord();
    if (status != OK){
      return status;
    }
  }

  return OK;
}


